<template>
  <div class="content">
    <!-- <div class="nav">
      <van-nav-bar
        title="授权登录"
        @click-left="router.back()"
        style="background-color: transparent"
      >
        <template #left>
          <van-icon name="arrow-left" size="24" color="#333" />
        </template>
</van-nav-bar>
</div> -->
    <div class="top flex-column">
      <div class="logo flex-row">
        <div class="icon">
          <img src="/src/assets/icon/logo.png" alt="" />
        </div>
        <div class="title">二当家达人</div>
      </div>
      <!-- <transition name='fade'> -->
      <div class="tabs flex-row">
        <!-- 动态绑定active类名 -->
        <div
          v-for="(item, index) in loginType"
          :key="index"
          class="tab"
          :class="{ active: loginIndex == index }"
          @click="loginIndex = index"
        >
          {{ item }}
        </div>
      </div>
      <!-- </transition> -->
    </div>
    <transition-group name="fade">
      <div class="form-login" v-if="loginIndex == 0">
        <div class="form-content">
          <van-field
            v-model="loginForm.phone"
            label="手机号"
            placeholder="请输入手机号码"
          />
        </div>
        <div class="form-content">
          <van-field
            v-model="loginForm.verifyCode"
            label="验证码"
            placeholder="请输入验证码"
          >
            <template #button>
              <div class="btn" @click="getCode()">{{ codeMesg }}</div>
            </template>
          </van-field>
        </div>
      </div>
      <div class="form-login" v-else>
        <div class="form-content">
          <van-field
            v-model="loginForm.phone"
            label="手机号"
            placeholder="请输入手机号码"
          />
        </div>
        <div class="form-content">
          <van-field
            :type="isShowPasd ? 'password' : 'text'"
            v-model="loginForm.password"
            label="密码"
            placeholder="请输入密码"
          >
            <template #button>
              <div
                class="eye flex-row"
                style="justify-content: center; align-items: center"
                @click="isShowPasd = !isShowPasd"
              >
                <van-icon :name="isShowPasd ? 'closed-eye' : 'eye-o'" size="18" />
              </div>
            </template>
          </van-field>
        </div>
        <div class="forget" @click="goForget()">忘记密码？</div>
        <!-- <div class="forget"> </div> -->
      </div>
    </transition-group>
    <div class="foot">
      <div class="choose flex-row">
        <div class="choose_icon">
          <van-checkbox
            icon-size="12"
            checked-color="#eb6069"
            v-model="checkedArgee"
          />
        </div>
        <div class="font">
          勾选同意<span style="color: #fe6b6c">《用户服务协议》</span>
        </div>
      </div>
      <div
        class="log_btn"
        :class="{ log_btn_disable: !loginForm.phone.length }"
        @click="handleLogin()"
      >
        登录
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  showSuccessToast,
  showLoadingToast,
  closeToast,
  showToast,
} from "vant";
import { loginStore } from "@/store/login";
import { login, getSms, smsLogin } from "@/api/loginApi";
import { ref } from "vue";
import router from "@/router";
const checkedArgee = ref(false);
const codeMesg = ref("发送验证码");
const loginIndex = ref(0);
const loginType = ["短信登录", "账密登录"];
const sendType = ref(true);
const isShowPasd = ref(true);
const loginForm = ref({
  phone: "",
  password: "",
  verifyCode: "",
});
// 验证账号密码
const handleInspection = () => {
  if (loginForm.value.phone && loginForm.value.password) {
    // 手机号正则表达式
    const phoneReg = /^1[3-9]\d{9}$/;
    if (!phoneReg.test(loginForm.value.phone)) {
      showToast("请输入正确的手机号");
      return false;
    } else {
      if (checkedArgee.value) {
        return true;
      } else {
        showToast("请先勾选用户服务协议");
      }
    }
  } else {
    showToast("请输入手机号或密码");
    return false;
  }
};
// 短信验证登录
const messageLogin = async () => {
  if (loginForm.value.verifyCode.length) {
    showLoadingToast({ message: "登录中...", duration: 10000 });
    const res = await smsLogin({
      phone: loginForm.value.phone,
      smsCode: loginForm.value.verifyCode,
      commonParams: {
        appid: "wx465aabf338babebc",
      },
    }).catch(() => {
      closeToast();
    });
    if (res && res.code == 200) {
      closeToast();
      setStore(res.data?.oldToken,res.data?.token);
      showSuccessToast("登录成功");
      router.push({ name: "User" });
    }
  } else {
    showToast("请输入验证码");
  }
};
// 获取验证码前校验
const verfyPhone = () => {
  const phoneReg = /^1[3-9]\d{9}$/;
  if (phoneReg.test(loginForm.value.phone)) {
    return true;
  } else {
    showToast("请输入正确的手机号码");
  }
};
// 账密登录
const accountLogin = async () => {
  if (handleInspection()) {
    showLoadingToast({ message: "登录中...", duration: 10000 });
    const { phone, password } = loginForm.value;
    const parmData = {
      phone,
      password,
      commonParams: {
        appid: "wx465aabf338babebc",
      },
    };
    const res = await login(parmData).catch(() => {
      closeToast();
    });
    if (res && res.code == 200) {
      closeToast();
      setStore(res.data?.oldToken,res.data?.token);
      showSuccessToast("登录成功");
      router.push({ name: "User" });
    }
  }
};
// 写入pinia
const setStore = (token: string,newToken:string) => {
  const login = loginStore();
  login.setToken(token);
  login.setNewToken(newToken);
};
// 登录按钮
const handleLogin = () => {
  // 账号登录
  if (loginIndex.value == 1) {
    accountLogin();
  } else {
    messageLogin();
  }
};

// 获取验证码
const getSmsNum = async () => {
  const { phone } = loginForm.value;
  const res = await getSms({
    phone,
    scene: "LOGIN",
  });
  if (res && res.code == 200) {
    showToast("短信发送成功");
  }
};
const getCode = () => {
  // 发送验证码
  if (sendType.value && verfyPhone()) {
    sendType.value = false;
    getSmsNum();
    codeMesg.value = "60秒后重新发送";
    let time = 59;
    let timer = setInterval(() => {
      if (time == 0) {
        clearInterval(timer);
        codeMesg.value = "重新发送";
        sendType.value = true;
      } else {
        codeMesg.value = time + "秒后重新发送";
        time--;
      }
    }, 1000);
  }
};
// 跳转忘记密码
const goForget = () => {
  router.push('/forget');
};
</script>

<style lang="less" scoped>
@import "./login.less";
</style>
